import React, { Component } from 'react';
import { Upload, Modal, message } from 'antd';
import { connect } from 'umi'
import { PlusOutlined } from '@ant-design/icons';


import { reqDeleteImg } from '../service'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

class PicturesWall extends Component {

  constructor(props) {
    super(props)
    let fileList = []
    // 如果传入了imgs
    const { product: { imgs }, BASE_URL_IMG } = props
    imgs && imgs.length > 0 ? (
      fileList = imgs.map((img, index) => ({
        uid: -index,
        name: img,
        status: 'done',
        url: `${BASE_URL_IMG}${img}`,
      }))
    ) : null
    this.state = {
      previewVisible: false, // 标识是否大图预览modal
      previewImage: '',  // 大图预览src地址
      fileList,
    }
  }

  handleCancel = () => this.setState({ previewVisible: false });

  // 显示指定图片的大图预览
  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };

  handleChange = async ({ file, fileList }) => {
    // 一旦上传成功,就修正file的信息(name, url)
    if (file.status === 'done') {
      const { status, data, msg } = file.response
      if (status === 0){
        message.success('图片上传成功')
        const { name, url } = data
        file = fileList[fileList.length - 1]
        file.name = name
        file.url = url
      }else {
        message.error(msg)
      }
    }else if (file.status === 'removed') {
      const { status, msg } = await reqDeleteImg({
        payload: {
          data: {name: file.name}
        }
      })
      if (status === 0) {
        message.success('图片删除成功')
      }else {
        message.error(msg)
      }
    }
    this.setState({ fileList }, () => {
      const { dispatch } = this.props
      const imgs = fileList.map(file => file.name)
      dispatch({
        type: 'product/save',
        payload: {
          imgs
        }
      })
    })
  };

  render() {
    const { previewVisible, previewImage, fileList, previewTitle } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>上传</div>
      </div>
    );
    return (
      <>
        <Upload
          action="/api1/manage/img/upload"
          listType="picture-card"
          name='image'
          accept='image/*'
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {fileList.length >= 3 ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          // title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="image" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    );
  }
}

export default connect(({ product }) => ({
  ...product
}))(PicturesWall)
